import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../screens/home/model/comic_category_item_model.dart';
import '../screens/home/model/comic_detail_model.dart';
import '../utils/http_helper.dart';

// Comic Detail Provider
final comicDetailProvider = StateNotifierProvider.family<ComicDetailNotifier,
    AsyncValue<ComicDetailModel>, String>((ref, comicId) {
  return ComicDetailNotifier(comicId);
});

class ComicDetailNotifier extends StateNotifier<AsyncValue<ComicDetailModel>> {
  final String comicId;

  ComicDetailNotifier(this.comicId) : super(const AsyncValue.loading()) {
    _loadComicDetail();
  }

  Future<void> _loadComicDetail() async {
    try {
      state = const AsyncValue.loading();

      final userResponse = await HttpUtil().getModel<ComicDetailModel>(
        'Comic/GetComicDetail',
        params: {"comicId": comicId},
        fromJson: (json) =>
            ComicDetailModel.fromJson(json as Map<String, dynamic>),
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        state = AsyncValue.data(userResponse!.result!);
      } else {
        state = AsyncValue.error(
            'Failed to load comic details', StackTrace.current);
      }
    } catch (error, stackTrace) {
      state = AsyncValue.error(error, stackTrace);
    }
  }

  // 添加收藏功能
  Future<bool> addToFavorites() async {
    try {
      final response = await HttpUtil().postJson(
        'Comic/AddComicFavorites',
        data: {"comicId": comicId},
      );
      print("object = ${response}");
      if (response?['status'] == 200) {
        // 收藏成功后，更新本地状态
        final currentState = state;
        if (currentState is AsyncData<ComicDetailModel>) {
          final currentData = currentState.value;
          if (currentData.comic != null) {
            // 创建新的ComicItemModel，增加favoriteNum
            final updatedComic = ComicItemModel(
              author: currentData.comic!.author,
              bookRating: currentData.comic!.bookRating,
              status: currentData.comic!.status,
              comicType: currentData.comic!.comicType,
              categoryId: currentData.comic!.categoryId,
              title: currentData.comic!.title,
              desc: currentData.comic!.desc,
              cover: currentData.comic!.cover,
              favoriteNum: (currentData.comic!.favoriteNum ?? 0) + 1,
              readNum: currentData.comic!.readNum,
              type: currentData.comic!.type,
              viewNum: currentData.comic!.viewNum,
              recommendSort: currentData.comic!.recommendSort,
              countryCode: currentData.comic!.countryCode,
              isComplete: currentData.comic!.isComplete,
              id: currentData.comic!.id,
              key: currentData.comic!.key,
            );

            // 更新状态，将 isFavorite 设置为 true
            final updatedDetail = ComicDetailModel(
              updatedComic,
              currentData.comicChapters,
              true, // 收藏成功后设置为 true
              currentData.buyPrice,
              currentData.similarComic,
            );
            state = AsyncValue.data(updatedDetail);
          }
        }
        return true;
      } else {
        return false;
      }
    } catch (error) {
      print('Add to favorites error: $error');
      return false;
    }
  }

  // 检查是否已收藏（基于favoriteNum > 0判断）
  bool get isFavorited {
    final currentState = state;
    if (currentState is AsyncData<ComicDetailModel>) {
      return (currentState.value.isFavorite ?? false);
    }
    return false;
  }

  Future<void> refresh() async {
    await _loadComicDetail();
  }
}
